const app = document.getElementById('app');

function clean({ el, player } = {}) {
  if (player) {
    player.stopAnimation();
    player.clear();
    player.clearDynamicObjects();
  }

  if (el) {
    el.remove();
  }
}

function render(file) {
  // clean(render.stage);

  const el = document.createElement('div');
  const span = document.createElement('span');
  const player = new SVGA.Player(el);
  const parser = new SVGA.Parser(el);

  el.classList.add('svga');

  app.appendChild(el);
  el.appendChild(span);
  el.svga = { el, span, player };

  parser.load(file, function(videoItem) {
    const { width, height } = videoItem.videoSize;
    el.style.width = width + 'px';
    el.style.height = height + 'px';
    span.innerText = `${width}x${height} - ${file.size / 1024 | 0}kb`;

    player.setVideoItem(videoItem);
    player.startAnimation();
  });
}

app.addEventListener('dragover', function (e) {
  e.preventDefault();
});

app.addEventListener('drop', function (e) {
  const { files } = e.dataTransfer;

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    if (/\.svga/i.test(file.name)) {
      render(file);
      console.log(files[i]);
    }
  }

  e.preventDefault();
}, false);

const colors = document.querySelectorAll('.color');

[...colors].forEach((it) => {
  const bgc = getComputedStyle(it).backgroundColor;
  it.addEventListener('click', () => {
    document.body.style.setProperty('--svga-color', bgc);
  }, false);
});
